<template>
  <div id="customUnitReport">
    <!-- 表头信息对话框 -->
    <el-dialog
      title="填写其他信息"
      :visible.sync="headerInfoVisible"
      width="600px" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="headerInfo" label-width="120px" ref="headerForm" :rules="headerFormRules">
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="headerInfo.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 300px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="填报日期" prop="reportDate">
          <el-date-picker
            v-model="headerInfo.reportDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 180px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="headerInfo.contactName" style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="headerInfo.contactPhone" style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="updataHeaderInfo()" :loading="listLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="formShowVisible"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <unitFormShow :currentUnitname="currentUnitname" :projectId="projectId" :timestamp="timestamp" :readOnly="readonly" @saveUnitData="saveUnitData" :unitData="unitData" :project="project" />
    </el-dialog>
    <!-- 新增填报通知对话框 -->
    <el-dialog
      title="填报通知"
      :visible.sync="noticeVisible"
      @close="handleNoticeClose"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div style="font-size:var(--size16);line-height:150%;margin:0 20px;white-space: pre-line;">
        {{ project.projectRemark }}
        <hr>
        <b>附件：</b><br>
        <template v-if="project.fileList">
          <div v-for="(item,index) in project.fileList" :key="'file_'+index">
            <el-link :href="$http.defaults.baseURL+$http.defaults.supervisionAPI +'api/statsGenFileInfo/download?id='+item.id" target="_blank">{{item.fileName}}</el-link>
          </div>
        </template>
      </div>
    </el-dialog>
    <el-dialog
      title="填报说明"
      :visible.sync="infoShowVisible"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div style="font-size:var(--size16);line-height:150%;margin:0 20px;text-indent:2em;">
        <p>1．统计数据截止时间为2025年6月30日。</p>
        <p>2．本表格主要统计以下纪检机构及其中专门从事或者主要从事纪检工作的在编人员情况：中央和国家机关各部门机关纪委，以及中央和国家机关各部门所属单位、管理（监管、代管）单位，垂直管理单位（实行双重领导并以上级单位领导为主的单位）各级内设纪检机构。</p>
        <p>3．中央和国家机关党委（党组）巡视巡察机构中，专责履行巡视巡察职责的编制及实有人员情况，纳入本次统计。如存在列编在纪检机构内或由纪检机构统一管理的情形（不包括仅由纪检机构主要负责人分管或协管的情形），<b>需附件细化说明</b>。中央一级党政机关、企事业单位的二级及以下单位内设巡察机构编制人员不纳入本次统计。</p>
        <p>4．以下机构、人员不列入统计范围：①未在纪律检查机关担负具体工作的纪委委员；②党总支、党支部的纪检委员； ③其他兼职纪检干部；④借调人员、挂职人员、临时抽调人员、编外聘用人员；⑤离退休纪检干部。未在各级纪检机关担负具体工作的纪委委员、纪检委员不列入此次统计范围。</p>
        <p>5．“编制总数”应等于“行政编制”“事业编制”“企业编制”之和；暂未核定编制的，编制数按实有人数填写。存在其他编制或暂未核定编制的，<b>需附件细化说明</b>。</p>
        <p>6．“实有人员”，按照“专门从事或者主要从事纪检工作”把握，如有特殊情况请另附材料细化说明。“实有人数” 应等于“行政人员”“事业人员”“企业人员”之和。在纪检监察系统内兼任多个职务的，按其最高职务层次统计一次。避免遗漏或重复统计。</p>
        <p>7．“领导职数”“实际配备情况”栏中，“按职务层次分”填写相关单位部门核定的领导职数及配备情况，存在一名领导干部兼任多个职务的，需分别体现配备情况。</p>
        <p>8．“年龄结构”（不含平均年龄）“最高学历结构”分别合计数均应与“实有人数”相同。</p>
        <p>9．“最高学历结构”按获得的最高学历填写。最高学历不包括仅获得学位、无相应学历的情形。“高中及以下”包括中专、中技等。</p>
        <p>10．“在岗人员严重疾病情况”栏中，主要统计目前患有重大疾病、严重精神疾病以及导致无法正常到岗工作的其他严重疾病情况。其中，“重大疾病”可参照中国保险行业协会、中国医师协会发布的重大疾病定义的有关规定。填写本栏<b>需附件细化说明</b>人员姓名、性别、年龄、职务职级、所患疾病等情况。</p>
        <p>11．“在岗人员伤残情况”统计持有残疾人证人员，填写本栏<b>需附件细化说明</b>人员姓名、性别、年龄、职务职级、伤残缘由、程度等情况。</p>
        <p>12．“在岗人员死亡情况”中，除烈士、因公牺牲以外情况的（如自杀身亡、病故），均在“其他”中填写。因工死亡人员在“因公牺牲”中填写。因公牺牲、因工死亡人员需经有关部门根据规定予以确认。填写以上3项<b>需附件细化说明</b>人员姓名、年龄、职务职级、死亡时间、原因等情况。</p>
        <p>13．“垂管单位”中，一并统计“双重领导并以上级单位领导为主”的情况。其中，垂管单位省级纪检机构“机构数”栏，统计实行垂直管理或者双重领导并以上级单位领导为主的中央和国家机关下一级单位纪检机构数量，不统计其他分支机构数量。</p>
        <p>14．如有其他情况，可附说明，请勿改变表格样式。</p>
      </div>
    </el-dialog>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/supervision/unitProjectList' }">干部监督填报</el-breadcrumb-item>
    </el-breadcrumb>
    <section class="wboxs">
    <!--工具条-->
      <h1>项目名称：{{project.projectTitle}}</h1>
      <el-popconfirm
        @confirm="saveData"
        @onConfirm="saveData"
        icon="el-icon-info"
        icon-color="red"
        title="确定提交所填信息吗？"
      >
        <el-button slot="reference" type="warning" :loading="dataLoading" icon="el-icon-s-promotion" style="float:right;margin:10px;">提交</el-button>
      </el-popconfirm>
      <el-button type="primary" @click="showHeaderInfo" icon="el-icon-document" style="float:right;margin:10px 5px;">其他信息</el-button>
      <el-button type="success" @click="addnew" icon="el-icon-plus" style="float:right;margin:10px 5px;">新增人员证件信息</el-button>
      <!-- <el-button type="info" @click="showInfo" icon="el-icon-warning-outline" style="float:right;margin:10px 5px;">查看填报说明</el-button> -->
      <el-button type="primary" @click="getSingleUnitData" icon="el-icon-download" style="float:right;margin:10px 5px;">数据导出</el-button>
      <el-upload id="confirmUpload"
        style="float:right;margin:10px 5px;" class="upload-demo" :before-upload="beforeAvatarUpload" :on-success="getImportList" name="file" :file-list="fileList" :show-file-list="false"
        :action="this.$http.defaults.baseURL + this.$http.defaults.supervisionAPI + 'api/statsReportData/saveImport?reportDataId=' + $route.params.id" with-credentials :on-error='uploaderror' accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <button type="primary" style="display:none" ref="importUploadButton">选择文件</button>
      </el-upload>
      <el-popconfirm
        title="数据导入操作会清除当前项目全部已填写数据，确认要导入吗？"
        confirm-button-text="确定"
        cancel-button-text="取消"
        type="warning"
        @onConfirm="handleConfirm"
        @confirm="handleConfirm"
      >
        <el-button id="confirmUploadBtn" type="success" icon="el-icon-upload2" style="float:right;margin:10px 5px;" slot="reference">数据导入</el-button>
      </el-popconfirm>
      <el-button type="primary" @click="getTemplate" icon="el-icon-document" style="float:right;margin:10px 5px;">下载模板</el-button>
      <el-button v-if="showNoticeBtn" type="info" @click="noticeVisible = true" icon="el-icon-bell" style="float:right;margin:10px 5px;">查看填报通知</el-button>
      <div style="line-height:200%;margin:10px;">
        填报起止日期：{{project.beginDate}} 至 {{project.endDate}}
      </div>
    </section>
    <!--列表-->
    <section class="unitbox" style="margin-top:10px">
      <el-table :data="list" highlight-current-row v-loading="listLoading" style="width: 100%;" :height="tableHeight" border
        ref="multipleTable"
        >
        <el-table-column type="index" label="序号" width="60" align="center" class-name="tableth">
        </el-table-column>
        <el-table-column label="姓名" width="80" prop="realname" align="center"/>
        <el-table-column label="性别" width="80" prop="gender" align="center"/>
        <el-table-column label="所属部门或单位" width="180" prop="department" show-overflow-tooltip />
        <el-table-column label="三级单位及部门" prop="unitname" show-overflow-tooltip />
        <el-table-column label="职务级别" width="180" prop="level" align="center"/>
        <el-table-column label="职务" width="100" prop="job" align="center"/>
        <el-table-column label="职务职级/专业技术等级" width="170" prop="joblevel" align="center"/>
        <el-table-column label="是否在职" width="80" prop="inposition" align="center"/>
        <el-table-column label="是否登记备案人员" width="140" prop="registered" align="center"/>
        <el-table-column label="手机联系方式（个人手机）" width="190" prop="phone" align="center"/>
        <el-table-column label="保管单位" width="130" prop="custodian" align="center"/>
        <el-table-column label="操作" width="350" align="center">
          <template slot-scope="scope">
            <el-button @click="detail(scope.row.id)" type="success" size="mini" style="margin:10px 0">登记备案人员出国境情况</el-button>
            <el-button @click="edit(scope.row)" type="primary" size="mini" style="margin:10px 0">修改</el-button>
            <el-popconfirm
              @confirm="del(scope.row.id)"
              @onConfirm="del(scope.row.id)"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除本条信息吗？"
            >
              <el-button type="danger" slot="reference" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </section>
  </div>
</template>

<script>
import unitFormShow from './customUnitFormShow'
export default {
  components: {
    unitFormShow
  },
  data () {
    return {
      headerInfoVisible: false,
      headerInfo: {
        timeRange: [],
        reportDate: '',
        contactName: '',
        contactPhone: ''
      },
      headerFormRules: {
        timeRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
        reportDate: [{ required: true, message: '请选择填报日期', trigger: 'change' }],
        contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
        contactPhone: [{
          required: true,
          message: '请输入联系人电话',
          trigger: 'blur'
        }]
      },
      fileList: [],
      initLoading: false,
      unitDataFlag: false,
      unitData: {},
      infoShowVisible: false,
      pageNum: 1,
      pageSize: 20,
      totalnum: 0,
      Isace: true,
      Sortkey: '',
      limitNum: '',
      index: -1,
      formShowVisible: false,
      timestamp: '',
      projectId: null,
      dialogTitle: '新增',
      items: [],
      unitname: '',
      project: {},
      listLoading: true,
      dataLoading: true,
      tableHeight: 100,
      list: [
      ],
      changeSizeFlag: false,
      readonly: false,
      item: {},
      fileIds: [],
      noticeVisible: false,
      showNoticeBtn: false,
      currentUnitname: ''
    }
  },
  methods: {
    getCurrentUnitname () {
      this.$http.get(this.$http.defaults.baseURL + this.$http.defaults.supervisionAPI + 'api/statsReportData/getUnitName')
        .then(res => {
          if (res.data.success) {
            this.currentUnitname = res.data.result
            console.log(this.currentUnitname)
          } else {
            this.$message.error('获取单位名称失败' + res.data.message)
          }
        })
    },
    updataHeaderInfo () {
      // 更新表头信息
      this.$refs.headerForm.validate((valid) => {
        if (valid) {
          this.updataUnitData()
        } else {
          console.log('校验失败')
          return false
        }
      })
    },
    showHeaderInfo () {
      this.headerInfoVisible = true
    },
    handleConfirm () {
      this.$refs.importUploadButton.click()
    },
    handleNoticeClose () {
      if (this.noticeStorageKey) {
        localStorage.setItem(this.noticeStorageKey, 'true')
      }
    },
    uploaderror (err) {
      console.log('具体错误')
      console.log(err)
      this.$message({
        message: '导入失败，可能是文件大小超出系统限制:' + err,
        type: 'error'
      })
    },
    beforeAvatarUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      const isFormat = file.name.indexOf('.xlsx') > 0
      // const isLt5M = file.size / 1024 / 1024 < 500
      if (!isFormat) {
        this.$message.error('上传文件只能是 .xlsx 格式!')
      }
      return isFormat
    },
    getSingleUnitData () {
      if (this.headerInfo.contactName) {
        window.open(this.$http.defaults.baseURL + this.$http.defaults.supervisionAPI + 'api/statsReportData/getSingleUnitData?reportDataId=' + this.$route.params.id)
      } else {
        this.$message.error('请填写其他信息')
      }
    },
    getTemplate () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.supervisionAPI + 'api/statsReportData/getTemplate')
    },
    detail (id) {
      this.$router.push('/supervision/customDeptDetail/' + this.$route.params.id + ',' + id)
    },
    del (id) {
      let para = {
        reportDataId: parseInt(this.$route.params.id),
        pageNum: 1,
        pageSize: 1,
        deptId: id
      }
      this.$http
        .post(this.$http.defaults.supervisionAPI + `api/statsReportDataItem/queryByPage`, para)
        .then(response => {
          if (response.data.result.total) {
            this.$message({
              message: '该人员已经有出国境情况信息，无法删除。请先点击查看人员登记备案人员出国境情况信息，删除该人员全部出国境情况信息，再进行删除人员操作',
              type: 'error'
            })
          } else {
            this.list.forEach((item, index, arr) => {
              if (item.id && item.id === id) {
                arr.splice(index, 1)
              }
            })
            this.updataUnitData()
          }
        })
        .catch(error => {
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    showInfo () {
      this.infoShowVisible = true
    },
    saveData () {
      if (!this.list || this.list.length === 0) {
        this.$message({
          message: '未添加人员证件信息',
          type: 'error'
        })
        return false
      }
      if (!this.headerInfo.contactName) {
        this.$message.error('请填写其他信息')
        return false
      }
      this.$http
        .get(this.$http.defaults.supervisionAPI + `api/statsReportData/submit?id=` + parseInt(this.$route.params.id))
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.$router.push('/supervision/unitProjectList')
          } else {
            this.$message({
              message: '提交失败:' + response.data.message,
              dangerouslyUseHTMLString: true,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.$message({
            message: '网络提交失败:' + error,
            type: 'error'
          })
        })
    },
    saveUnitData (data) {
      if (data.inposition === '否') {
        data.registered = '是'
        data.major = '否'
      }
      if (data.id) {
        this.list.forEach((item, index, arr) => {
          if (item.id && item.id === data.id) {
            arr[index] = data
          }
        })
      } else {
        this.list.push(data)
      }
      this.updataUnitData()
    },
    updataUnitData () {
      this.listLoading = true
      let para = {
        id: parseInt(this.$route.params.id),
        reportJson: {list: this.list},
        headerInfo: this.headerInfo.contactName ? this.headerInfo : null
      }
      this.$http
        .post(this.$http.defaults.supervisionAPI + `api/statsReportData/save`, para)
        .then(response => {
          this.listLoading = false
          if (response.data.success) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.list = JSON.parse(response.data.result).list
            this.formShowVisible = false
            this.headerInfoVisible = false
          } else {
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.listLoading = false
          this.$message({
            message: '网络操作失败:' + error,
            type: 'error'
          })
        })
    },
    addnew () {
      this.dialogTitle = '新增人员证件信息'
      this.index = -1
      this.timestamp = new Date().getTime()
      this.formShowVisible = true
      this.unitData = {
        realname: '',
        gender: '',
        unitname: '',
        level: '',
        job: '',
        joblevel: '',
        inposition: '',
        major: '',
        registered: '',
        docList: [
          {
            doctype: '',
            docnum: '',
            startdate: '',
            enddate: '',
            fulldate: []
          }
        ],
        phone: '',
        custodian: ''
      }
    },
    edit (item) {
      this.dialogTitle = '修改人员证件信息'
      this.timestamp = new Date().getTime()
      this.formShowVisible = true
      this.unitData = item
    },
    getProjectDetail () {
      this.dataLoading = true
      this.listLoading = true
      this.$http
        .get(this.$http.defaults.supervisionAPI + `api/statsProjectData/getById?id=` + this.projectId)
        .then(response => {
          this.project = response.data.result
          this.dataLoading = false
          this.listLoading = false
          let hasRemark = (this.project.projectRemark && this.project.projectRemark.trim() !== '') || (this.project.fileList && this.project.fileList.length > 0)
          console.log('是否为空：')
          // console.log(this.project.projectRemark)
          // console.log(this.project.projectRemark.trim())
          console.log(this.project.projectRemark.trim() !== '')
          console.log(this.project.projectRemark && this.project.projectRemark.trim() !== '')
          console.log(hasRemark)
          this.showNoticeBtn = !!hasRemark
          this.noticeStorageKey = `noticeShown_${this.$route.params.id}`
          const hasShown = JSON.parse(localStorage.getItem(this.noticeStorageKey))
          if (hasRemark && !hasShown) {
            this.noticeVisible = true
            localStorage.setItem(this.noticeStorageKey, 'true')
          }
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.dataLoading = false
          this.listLoading = false
        })
    },
    getImportList (res) {
      if (res.success) {
        this.$message({
          // message: `成功导入${res.result}条数据！`,
          message: res.result,
          type: 'success'
        })
        this.getProjectDataDetail()
      } else {
        this.$message({
          message: '导入失败:' + res.message,
          type: 'error'
        })
      }
    },
    getProjectDataDetail () {
      this.$http
        .get(this.$http.defaults.supervisionAPI + `api/statsReportData/getById?id=` + this.$route.params.id)
        .then(response => {
          this.projectId = response.data.result.projectId
          if (response.data.result.reportJson) {
            this.list = response.data.result.reportJson.list
          }
          if (response.data.result.headerInfo) {
            this.headerInfo = response.data.result.headerInfo
          }
          this.getProjectDetail()
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      let myheight = 249

      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - myheight
      })
    }
  },
  mounted () {
    // this.unitname = localStorage.getItem('Otherunitname')
    this.getCurrentUnitname()
    this.getProjectDataDetail()
    this.tableresize(this)
    window.onresize = () => {
      this.tableresize(this)
    }
  }
}
</script>
<style>
#customUnitReport .el-drawer__wrapper{
  width: 100%;
  height: 100%;
  position: fixed !important;
  overflow: hidden;
}
  .unitbox .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .unitbox .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  .tableth{
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    height:33px;
  }
  #testlist .wboxs{
    height:45px;
    padding-top:10px;
  }
  #customUnitReport .el-table td{
    border-right: 1px solid #95B8E7;
    border-bottom: 1px solid #95B8E7;
  }
  #customUnitReport .el-table__cell{
    border-right: 1px solid #95B8E7 !important;
    border-bottom: 1px solid #95B8E7 !important;
  }
#confirmUpload .el-upload::after{
  display: none;
}
#confirmUpload .el-upload::after{
  display: none;
}
#confirmUploadBtn{
  position: relative;
  display: inline-block;
}
#confirmUploadBtn::after{
  content: " ";
  font-size: 12px;
  z-index: 1;
  width: 140px;
  height: 20px;
  position: absolute;
  top: -30%;
  left: 30%;
  white-space: nowrap;
  pointer-events: none;
  background: url(../assets/tips.png) no-repeat;
}
#confirmUploadBtn:hover::after {
    display: none;
}
</style>
<style scoped>
  #customUnitReport .el-button{
    color:#fff !important;
  }
  #customUnitReport h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  .el-pagination{
    float: left;
    padding:7px 10px;
  }
  #customUnitReport .wboxs{
    width: 100%;
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
    padding:0;
  }
  .unitbox{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>
